package pooller.ui;

import com.google.gwt.core.client.GWT;
import com.google.gwt.editor.client.Editor;
import com.google.gwt.editor.client.SimpleBeanEditorDriver;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.VerticalPanel;
import pooller.dto.pool.PoolQuestionDto;
import pooller.dto.pool.QuestionVariantDto;

public class QuestionCell extends Composite implements Editor<PoolQuestionDto> {
    interface QuestionCellUiBinder extends UiBinder<VerticalPanel, QuestionCell> {}
    private static QuestionCellUiBinder uiBinder = GWT.create(QuestionCellUiBinder.class);
    @UiField
    VerticalPanel variantsContainer;
    @UiField
    Button addVariantBottom;
    @UiField
    TextArea questionTextEditor;

    interface Driver extends SimpleBeanEditorDriver<PoolQuestionDto, QuestionCell> {}
    Driver driver = GWT.create(Driver.class);

    private PoolQuestionDto questionDto;

    public QuestionCell() {
        initWidget(uiBinder.createAndBindUi(this));
        driver.initialize(this);
    }

    public PoolQuestionDto getQuestionDto() {
        return questionDto;
    }

    public void setQuestionDto(PoolQuestionDto questionDto) {
        this.questionDto = questionDto;
        addVariantBottom.setVisible(questionDto.getVariants().size() > 0);
        questionTextEditor.setText(questionDto.getQuestionText());
        if (questionDto != null) {
            for (QuestionVariantDto v : questionDto.getVariants()) {
                addVariant(v);
            }
        }
    }

    @UiHandler("addVariantBottom")
    public void addVariantBottomClick(ClickEvent event) {
        addVariant();
    }

    @UiHandler("addVariantTop")
    public void addVariantTopClick(ClickEvent event) {
        addVariant();
        addVariantBottom.setVisible(questionDto.getVariants().size() > 0);
    }

    private void addVariant() {
        QuestionVariantDto variantDto = new QuestionVariantDto();
        VariantCell variantCell = new VariantCell();
        variantCell.setVariantDto(variantDto);
        this.questionDto.getVariants().add(variantDto);
        variantsContainer.add(variantCell);
    }

    private void addVariant(QuestionVariantDto variantDto) {
        VariantCell variantCell = new VariantCell();
        variantCell.setVariantDto(variantDto);
        //this.questionDto.getVariants().add(variantDto);
        variantsContainer.add(variantCell);
    }
}
